﻿using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Xml;
using nTribeHR.Model;
using nTribeHR.Utilities;

namespace nTribeHR
{
    public class TribeHRUserRequestService : TribeHRServiceBase
    {
        
        public TribeHRUserRequestService(TribeHRConnection tribeHRConnection)
        {
            this.tribeHRConnection = tribeHRConnection;
        }

        private TribeHRUserRequestService()
        { }

        public IList<TribeUser> GetUsers()
        {
            XmlDocument xdoc = LoadXmlDocumentforUrl("/users.xml");
            return MapXmlGetUsersRequest(xdoc);
        }

        public int GetUserById(int id)
        {
            XmlDocument xdoc = LoadXmlDocumentforUrl(string.Format("/users/{0}.xml", id));

            int i = xdoc.ChildNodes.Count;

            return i;// MapXmlGetUserByIdRequest(xdoc);
        }


        private IList<TribeUser> MapXmlGetUsersRequest(XmlDocument xdoc)
        {
            List<TribeUser> result = null;

            using (ParseResultStopwatch = DisposableStopwatch.StartNew("Parse Results"))
            {
                XmlNode usersNode = xdoc.SelectSingleNode("/users");
                XmlNodeList users = usersNode.SelectNodes("user");
                result = new List<TribeUser>(users.Count);
                foreach (XmlNode user in users)
                {
                    result.Add(MapXmlUserNodeToTribeUser(user));
                }
            }

            return result;
        }

        private TribeUser MapXmlUserNodeToTribeUser(XmlNode user)
        {
            var tribeUser = TribeUser.Create(user);

            return tribeUser;
        }

    }
}
